//
//  Date+Ex.swift
//
//
//  Created by rui on 2024/5/7.
//

import Foundation

public extension Date {
    
    /// 格式化时间（转字符串）
    /// - Parameters:
    ///   - timeFormat: 格式化格式
    ///   - identifier: 地区
    /// - Returns: String
    static func currentTime(timeFormat: String = "YYYY-MM-dd HH:mm:ss.SSS") -> String {
        var date: Date;
        if #available(iOS 15, *) {
            date = Date.now
        } else {
            // Fallback on earlier versions
            date = Date()
        }
        return date.stringOfDate(withFormat: timeFormat)
    }
    
    /// 毫秒转换为date
    /// - Parameter millisecond: 毫秒
    /// - Returns: Date
    static func dateWithTimeMillisecondSince1970(_ millisecond: TimeInterval) -> Date {
        let timeInterval = millisecond / 1000
        return Date(timeIntervalSince1970: timeInterval)
    }
    
    /// 获取当前毫秒
    /// - Returns: TimeInterval
    func timeMillisecondSince1970() -> TimeInterval {
        let timeInterval = Date().timeIntervalSince1970
        return timeInterval * 1000
    }
    
    /// 获取当前微秒
    /// - Returns: TimeInterval
    func timeMilcrosecondSince1970() -> TimeInterval {
        let timeInterval = self.timeMillisecondSince1970()
        return timeInterval * 1000
    }
    
    /// Date转毫秒
    /// - Parameter date: Date
    /// - Returns: TimeInterval
    static func timeMillisecondSince1970(with date: Date) -> TimeInterval {
        let timeInterval = date.timeIntervalSince1970
        return timeInterval * 1000
    }
    
    /// 返回某天到当前相差的天数
    /// - Parameter date: Date
    /// - Returns: Int
    func daysDifferemt(from date: Date) -> Int {
        let d_day = 60*60*24
        let interval = self.timeIntervalSince(date)
        let days = Int(interval) / d_day
        return days
    }
    
    /// 获取时间的字符串格式
    /// - Parameters:
    ///   - string: 字符串格式
    ///   - identifier: 地区格式
    /// - Returns: 时间的字符串格式
    func stringOfDate(withFormat string: String = "YYYY-MM-dd", identifier: String = "Asia/Beijing") -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = string
        formatter.timeZone = TimeZone(identifier: identifier)
        let dateTime = formatter.string(from: self)
        return dateTime
    }
}
